const { think } = require('thinkjs');
const Base = require('./base.js');
const cid = require('@4a/cid');

module.exports = class extends Base {
  async listAction() {
    const query = {
      user_id: this.getLoginUserId() || 9159,
    };

    if (this.get('type') == 1) {
      query['p.status'] = 1;
      query['p.id'] = ['!=', null];
      const uData = await this.model('process')
        .order(['a.status ASC', 'a.id DESC'])
        .alias('a')
        .join({
          post_list: {
            join: 'left',
            as: 'p',
            on: ['job_id', 'id'],
          },
        })
        .distinct('a.job_id')
        .field('a.user_id, a.status as interview_status, a.interview_time, p.*')
        .where(
          Object.assign(
            {
              'a.interview_status': {
                '!=': null,
                '!=': 'INTERVIEW_FINISH',
              },
            },
            query
          )
        )
        .select();

      // const data = await this.model('process')
      //   .order(['a.id DESC'])
      //   .alias('a')
      //   .join({
      //     post_list: {
      //       join: 'left',
      //       as: 'p',
      //       on: ['job_id', 'id'],
      //     },
      //   })
      //   .distinct('a.job_id')
      //   .field(
      //     'a.user_id, a.ordertoken, a.create_time as process_time, a.status as interview_status, p.*'
      //   )
      //   .where(Object.assign({ 'a.sceneToken': null }, query))
      //   .select();

      // const newData = await this.model('index').getJobInfo(data);
      const newuData = await this.model('index').getJobInfo(uData);
      // for (const item of newData) {
      //   item.create_time = this.moment(item.process_time).format('MM-DD HH:mm');
      // }
      for (const item of newuData) {
        item.interview_time = this.moment(item.interview_time).format(
          'MM-DD HH:mm'
        );
      }

      // const hasVideo = await this.model('company_interview')
      //   .where({
      //     user_id: this.getLoginUserId(),
      //     status: ['IN', '0,1'],
      //   })
      //   .find();

      return this.success({
        uView: newuData,
        // hView: newData,
        // has: !think.isEmpty(hasVideo),
      });
    } else {
      const count = await this.model('process')
        .distinct('job_id')
        .alias('a')
        .join({
          post_list: {
            join: 'left',
            as: 'p',
            on: ['job_id', 'id'],
          },
        })
        .where(
          Object.assign(
            {
              _complex: {
                'a.sceneToken': null,
                'a.interview_status': {
                  '!=': null,
                  '!=': 'INTERVIEW_FINISH',
                },
                _logic: 'or',
              },
            },
            { 'p.status': 1, 'p.id': ['!=', null] },
            query
          )
        )
        .count();

      const uData = await this.model('process')
        .order(['a.status ASC', 'a.id DESC'])
        .alias('a')
        .join({
          post_list: {
            join: 'left',
            as: 'p',
            on: ['job_id', 'id'],
          },
        })
        .distinct('a.job_id')
        .field(
          'a.user_id, a.status as interview_status, a.ordertoken, a.interview_time, p.*'
        )
        .where(
          Object.assign(
            {
              'a.interview_status': 'INTERVIEW_FINISH',
              'p.id': ['!=', null],
            },
            query
          )
        )
        .select();

      // const data = await this.model('process')
      //   .order(['a.id DESC'])
      //   .alias('a')
      //   .join({
      //     post_list: {
      //       join: 'left',
      //       as: 'p',
      //       on: ['job_id', 'id'],
      //     },
      //   })
      //   .distinct('a.job_id')
      //   .field(
      //     'a.user_id, a.ordertoken, a.create_time as process_time, a.status as interview_status, p.*'
      //   )
      //   .where(Object.assign({ 'a.sceneToken': null }, query))
      //   .select();

      // const newData = await this.model('index').getJobInfo(data);
      const newuData = await this.model('index').getJobInfo(uData);
      // for (const item of newData) {
      //   item.create_time = moment(item.process_time).format('MM-DD HH:mm');
      // }
      for (const item of newuData) {
        item.interview_time = this.moment(item.interview_time).format(
          'MM-DD HH:mm'
        );
      }

      // const hasVideo = await this.model('company_interview')
      //   .where({
      //     user_id: this.getLoginUserId(),
      //     status: ['IN', '0,1'],
      //   })
      //   .find();

      return this.success({
        list: newuData,
        has: count,
        // has: !think.isEmpty(hasVideo),
      });
    }
  }

  async createInterviewAction() {
    const id = this.get('id');
    const company = this.get('company');

    const orderSn = cid(24);

    const has = await this.model('process')
      .where({
        user_id: this.getLoginUserId(),
        job_id: id,
        interview_status: 'INTERVIEW_FINISH',
      })
      .find();

    if (!think.isEmpty(has)) {
      return this.fail('已参加过该面试');
    }

    // if (think.isEmpty(company)) {
    //   const has = await this.model('process')
    //     .where({
    //       user_id: this.getLoginUserId(),
    //       job_id: id,
    //       status: 3,
    //     })
    //     .find();

    //   if (!think.isEmpty(has)) {
    //     return this.fail('已参加过该面试');
    //   }
    // } else {
    //   const has = await this.model('process')
    //     .where({
    //       user_id: this.getLoginUserId(),
    //       job_id: id,
    //       company_id: company,
    //       status: ['!=', 0],
    //     })
    //     .find();

    //   if (!think.isEmpty(has)) {
    //     return this.fail('已参加过该面试');
    //   }
    // }

    const job = await this.model('post_list').where({ id: id }).find();

    const hasInterview = await this.model('process')
      .where({
        user_id: this.getLoginUserId(),
        job_id: id,
        // status: ['!=', 3],
        interview_status: ['!=', 'INTERVIEW_FINISH'],
      })
      .find();

    // if (
    //   !think.isEmpty(hasInterview) &&
    //   hasInterview.interview_status === null
    // ) {
    //   console.log(2222)
    //   await this.model('process')
    //     .where({ id: hasInterview.id })
    //     .limit(1)
    //     .delete();
    // }
    if (
      !think.isEmpty(hasInterview) &&
      hasInterview.interview_status !== 'INTERVIEW_FINISH'
    ) {
      return this.success({
        data: encodeURIComponent(
          JSON.stringify({
            interviewToken: hasInterview.sceneToken,
          })
        ),
        id: hasInterview.id,
      });
    } else if (think.isEmpty(hasInterview)) {
      let aiModel;
      const modelArr = job.aiModel.split(',');
      if (modelArr.length === 1) {
        aiModel = modelArr[0];
      } else {
        var randomNum = Math.ceil(Math.random() * (modelArr.length - 1));
        aiModel = modelArr[randomNum];
      }

      const aiInterview = await this.service('process', 'admin').create(
        orderSn,
        aiModel
      );

      const addData = { user_id: this.getLoginUserId(), job_id: id, type: 1 };

      if (!think.isEmpty(company)) {
        addData.company_id = company;
      }

      Object.assign(addData, aiInterview.data.success[0]);
      addData.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
      addData.aiModel = aiModel;
      const newId = await this.model('process').add(addData);
      //面试人数+++
      this.model('post_list').where({ id: id }).increment('interview', 1);
      return this.success({
        data: encodeURIComponent(
          JSON.stringify({
            interviewToken: aiInterview.data.success[0].sceneToken,
          })
        ),
        id: newId,
      });
    }
  }

  async bookInterviewAction() {
    const id = this.get('id');

    const job = await this.model('post_list').where({ id: id }).find();

    const addData = { user_id: this.getLoginUserId(), job_id: id, type: 1 };

    addData.create_time = ['exp', 'CURRENT_TIMESTAMP()'];
    addData.aiModel = job.aiModel;

    await this.model('process')
      .where({ user_id: this.getLoginUserId(), job_id: id, type: 1 })
      .delete();

    await this.model('process').add(addData);

    //面试人数+++
    this.model('post_list').where({ id: id }).increment('interview', 1);

    return this.success();
  }

  async updateInterviewAction() {
    const id = this.get('id');
    const interviewStatus = this.get('interviewStatus');

    if (interviewStatus === 'CHEAT_WARN') {
      await this.model('process')
        .where({
          id: id,
        })
        .increment('warn', 1);
    } else {
      const has = await this.model('process')
        .where({
          id: id,
        })
        .find();

      if (!think.isEmpty(interviewStatus) && !think.isEmpty(has)) {
        await this.model('process')
          .where({
            id: id,
          })
          .update({
            interview_status: interviewStatus,
            interview_time: ['exp', 'CURRENT_TIMESTAMP()'],
          });
      }

      // if (interviewStatus === 'INTERVIEW_FINISH') {
      //   this.model('user_list')
      //     .where({ id: info.user_id })
      //     .increment('interview', 1);
      // }
    }

    return this.success();
  }

  async getReportAction() {
    const id = this.get('id');

    const has = await this.model('process')
      .where({
        user_id: this.getLoginUserId(),
        job_id: id,
      })
      .find();

    if (has.status === 0) {
      return this.success({
        status: 0,
      });
    } else if (has.status === 1 || has.status === 2) {
      return this.success({
        status: 1,
      });
    } else if (has.status === 3) {
      const reprotInterview = await this.service('process', 'admin').report(
        has.orderToken
      );

      return this.success({
        status: 2,
        reprot: reprotInterview,
      });
    }
    return this.success();
  }

  async getReportByTokenAction() {
    const id = this.get('id');

    const has = await this.model('process')
      .alias('a')
      .join({
        post_list: {
          join: 'left',
          as: 'p',
          on: ['job_id', 'id'],
        },
      })
      .where({
        'a.orderToken': id,
      })
      .field('a.*, p.name')
      .find();

    if (has.status === 0) {
      return this.success({
        status: 0,
      });
    } else if (has.status === 1 || has.status === 2) {
      return this.success({
        status: 1,
      });
    } else if (has.status === 3) {
      let user;
      if (this.get('user')) {
        user = await this.model('user_list')
          .where({ id: has.user_id })
          .field(
            'name, phone, birth, money, gender, avatar, job, city, job_city, money'
          )
          .find();
        if (user.birth) {
          user.age = this.moment().diff(user.birth, 'years');
        }
        if (user.phone) {
          user.phone = user.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
        }
      }
      const reprotInterview = await this.service('process', 'admin').report(
        has.orderToken
      );
      if (reprotInterview.data.list[0]) {
        reprotInterview.data.list[0].startTime = this.moment(
          reprotInterview.data.list[0].startTime * 1000
        ).format('YYYY-MM-DD HH:MM');
        reprotInterview.data.list[0].read = has.read;
      }
      this.model('process')
        .where({
          orderToken: id,
        })
        .increment('read', 1);

      reprotInterview.data.list[0].showVideo = true;

      return this.success({
        status: 2,
        job_name: has.name,
        report: reprotInterview.data.list[0],
        userinfo: user,
      });
    }
    return this.success();
  }
};
